package cn.gan.loveofsoul.controller;

import cn.gan.loveofsoul.commons.result.ErrorMessage;
import cn.gan.loveofsoul.commons.result.Result;
import cn.gan.loveofsoul.commons.result.StatusCode;
import cn.gan.loveofsoul.commons.utils.StringUtils;
import cn.gan.loveofsoul.entity.PhotoAlbum;
import cn.gan.loveofsoul.entity.PhotoUploadRecord;
import cn.gan.loveofsoul.entity.Relationship;
import cn.gan.loveofsoul.entity.vo.PhotoAlbumVO;
import cn.gan.loveofsoul.exception.BusinessException;
import cn.gan.loveofsoul.service.IPhotoAlbumService;
import cn.gan.loveofsoul.service.IPhotoUploadRecordService;
import cn.gan.loveofsoul.service.IRelationshipService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ganwh
 * @since 2023-10-26
 */
@Controller
@RequestMapping("/photoAlbum")
public class PhotoAlbumController {

    @Autowired
    private IPhotoAlbumService photoAlbumService;
    @Autowired
    private IPhotoUploadRecordService photoUploadRecordService;
    @Autowired
    private IRelationshipService relationshipService;

    /**
     * 功能描述: 分页查询相册列表
     *
     * @param pageIndex
     * @param pageSize
     * @param userId
     * @return cn.gan.loveofsoul.commons.result.Result
     * @author ganwh 2023/11/8 18:31
     */
    @GetMapping("/")
    @ResponseBody
    public Result queryList(@RequestParam(value = "pageIndex", defaultValue = "0") Integer pageIndex,
                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                            Integer userId) {
        if (Objects.isNull(userId)) {
            throw new BusinessException(StatusCode.BAD_REQUEST, ErrorMessage.MISSING_PARAMETER);
        }
        Relationship relationship = relationshipService.queryUserRelationship(userId);
        if (Objects.isNull(relationship)) {
            throw new BusinessException(StatusCode.NOT_FOUND, ErrorMessage.HAS_NO_RELATIONSHIP);
        }
        Page<PhotoAlbum> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<PhotoAlbum> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PhotoAlbum::getRelationshipId, relationship.getId());
        wrapper.orderByDesc(PhotoAlbum::getCreateTime);
        page = photoAlbumService.page(page, wrapper);
        List<PhotoAlbum> photoAlbumList = page.getRecords();
        List<PhotoAlbumVO> photoAlbumVOList = photoAlbumList.stream().map(photoAlbum -> {
            PhotoAlbumVO photoAlbumVO = BeanUtil.copyProperties(photoAlbum, PhotoAlbumVO.class);
            LambdaQueryWrapper<PhotoUploadRecord> recordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            recordLambdaQueryWrapper.eq(PhotoUploadRecord::getAlbumId, photoAlbumVO.getId());
            recordLambdaQueryWrapper.orderByDesc(PhotoUploadRecord::getUploadTime);

            long photoCount = photoUploadRecordService.count(recordLambdaQueryWrapper);
            photoAlbumVO.setPhotoCount(photoCount);

            List<PhotoUploadRecord> photoList = photoUploadRecordService.list(recordLambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(photoList)) {
                photoAlbumVO.setPhotoList(CollectionUtil.sub(photoList, 0, 1));
            }
            return photoAlbumVO;
        }).collect(Collectors.toList());

        Page<PhotoAlbumVO> pageResult = new Page<>(pageIndex, pageSize);
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(photoAlbumVOList);
        pageResult.setCurrent(page.getCurrent());
        return new Result(StatusCode.SUCCESS, ErrorMessage.SUCCESS, pageResult);
    }

    /**
     * 功能描述: 新建相册
     *
     * @param photoAlbumVO
     * @return cn.gan.loveofsoul.commons.result.Result
     * @author ganwh 2023/11/8 18:34
     */
    @PostMapping("/")
    @ResponseBody
    public Result add(@RequestBody @Valid PhotoAlbumVO photoAlbumVO) {
        LambdaQueryWrapper<PhotoAlbum> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PhotoAlbum::getRelationshipId, photoAlbumVO.getRelationshipId());
        wrapper.eq(PhotoAlbum::getAlbumName, photoAlbumVO.getAlbumName());
        long count = photoAlbumService.count(wrapper);
        if (count > 0) {
            throw new BusinessException(StatusCode.ERROR, "相册名称已存在");
        }
        PhotoAlbum newPhotoAlbum = BeanUtil.copyProperties(photoAlbumVO, PhotoAlbum.class);
        newPhotoAlbum.setCreateTime(LocalDateTime.now());
        photoAlbumService.save(newPhotoAlbum);
        return new Result(StatusCode.SUCCESS, ErrorMessage.SUCCESS, newPhotoAlbum);
    }

    /**
     * 功能描述: 修改相册名称
     *
     * @param photoAlbumVO
     * @return cn.gan.loveofsoul.commons.result.Result
     * @author ganwh 2023/11/8 18:42
     */
    @PutMapping("/")
    @ResponseBody
    public Result update(@RequestBody PhotoAlbumVO photoAlbumVO) {
        if (Objects.isNull(photoAlbumVO.getId()) || StringUtils.isBlank(photoAlbumVO.getAlbumName())) {
            throw new BusinessException(StatusCode.BAD_REQUEST, ErrorMessage.MISSING_PARAMETER);
        }
        LambdaUpdateWrapper<PhotoAlbum> wrapper = new LambdaUpdateWrapper<PhotoAlbum>()
                .set(PhotoAlbum::getAlbumName, photoAlbumVO.getAlbumName())
                .eq(PhotoAlbum::getId, photoAlbumVO.getId());
        photoAlbumService.update(wrapper);
        return new Result(StatusCode.SUCCESS, ErrorMessage.SUCCESS);
    }

    /**
     * 功能描述: 删除相册
     *
     * @param albumId
     * @return cn.gan.loveofsoul.commons.result.Result
     * @author ganwh 2023/11/8 18:44
     */
    @DeleteMapping("/")
    @ResponseBody
    public Result delete(@RequestBody Integer albumId) {
        if (Objects.isNull(albumId)) {
            throw new BusinessException(StatusCode.BAD_REQUEST, ErrorMessage.MISSING_PARAMETER);
        }
        photoAlbumService.removeById(albumId);
        return new Result(StatusCode.SUCCESS, ErrorMessage.SUCCESS);
    }
}
